<template>
  <!-- 保证金管理 -->
  <div>
    <!-- <div v-if="flag === 'edit'" class="top-btn-group">
      <el-button type="primary" size="mini" @click="handleSave">保存</el-button>
      <el-button size="mini" @click="handleBack">取消</el-button>
    </div> -->
    <search-form
      ref="searchBar"
      :search-config="searchConfig"
      :label-width="120"
      @clear="clearSearch"
      @search="handleSearch"
    />
    <div>
      <div class="btn-group">
        <el-button v-if="flag === 'edit'" type="primary" size="mini" @click="handleEdit">新增</el-button>
        <el-button v-if="flag === 'edit'" type="primary" size="mini" @click="handleImport">导入</el-button>
        <el-button type="primary" size="mini" @click="handleExport">导出</el-button>
      </div>
      <table-box
        ref="MarginManagement"
        v-loading="tableLoading"
        :selected-arry.sync="tableSelected"
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :data="tableData"
        :table-span-method="objectSpanMethod"
        :off-set="-20"
        show-index
        show-selection
        no-request
        @selection-change="selectionChangeHandle"
      >
        <el-table-column fixed="right" label="操作" min-width="200">
          <template slot-scope="scope">
            <el-button v-if="scope.row.attachmentName" type="text" size="small" @click="handlePreview(scope.row)">附件预览</el-button>
            <el-button v-if="scope.row.attachmentName" type="text" size="small" @click="downLoadFile(scope.row)">附件下载</el-button>
          </template>
        </el-table-column>
      </table-box>
    </div>
    <div>
      <import-files v-if="importVisible" title="导入" :visible.sync="importVisible" :config="fileImportConfig" @success="handleImportSuccess" />
      <export-files v-if="exportVisible" title="导出" :config="exportConfig" :visible.sync="exportVisible" @success="handleExportSuccess" />
    </div>
    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="urlList"
    />
    <add-margin v-if="showAdd" ref="addFinishedPlan" :visible.sync="showAdd" :detail-data="activatedData" @goBack="goHome" @success="getTableData(queryData)" />
  </div>
</template>

<script>
// import { createDownload } from '@/utils'
// import { exportAddFinishTable } from '@/api/marketConstruction'
import { getMarginData } from '@/api/constructionUnitMng'
import addMargin from './addMargin.vue'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  name: 'MarginManagement',
  components: { addMargin, ElImageViewer },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      exportVisible: false,
      importVisible: false,
      tableLoading: false,
      showViewer: false,
      urlList: [],
      flag: '',
      formData: {},
      tableData: [],
      queryData: new FormData(),
      showAdd: false,
      activatedData: [],
      searchConfig: [
        {
          label: '变更类型',
          prop: 'changeType',
          type: 'select',
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/CHANGE_TYPE?appCode=slm&domainCode=marketing`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        },
        {
          label: '变更项目',
          prop: 'changeItem',
          type: 'select',
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/CHANGE_ITEM?appCode=slm&domainCode=marketing`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        },
        { label: '变更金额', prop: 'amount', type: 'text', value: '', placeholder: '' },
        { label: '变更日期', prop: 'lastUpdateTime', type: 'date', value: '', placeholder: '' },
        {
          label: '门店',
          prop: 'shopCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'get',
            remoteUrl: '/select-service/api/v1/shop/page',
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '门店',
            interfacePath: '/select-service/api/v1/shop/page',
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '发函部门',
          prop: 'sendLetterDeptCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'get',
            remoteUrl: `${process.env.VUE_APP_BASE_API}/api/v1/remoteUser/organization/domain/marketing/tree/orgType`,
            paramField: 'type', // 远程搜索参数名
            defaultProps: {
              label: 'orgName',
              value: 'orgCode'
            },
            selectData: []
          },
          dialogConfig: {
            title: '发函部门',
            method: 'get',
            paramField: 'type',
            interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/remoteUser/organization/domain/marketing/tree/orgType`,
            setting: [{ prop: 'orgCode', title: '编码' }, { prop: 'orgName', title: '名称' }],
            pageFlag: true
          }
        },
        { label: '门店建设项目号', prop: 'constCode', type: 'text', value: '', placeholder: '' }
      ],
      filterArr: [],
      tableSelected: [],
      otherFilters: [],
      tableConfig: {
        // interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/constUnitMargin/page`,
        hideFuncBar: true,
        setting: [
          {
            prop: 'changeType',
            label: '变更类型',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'CHANGE_TYPE'
            },
            minWidth: '100'
          },
          {
            prop: 'changeItem',
            label: '变更项目',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'CHANGE_ITEM'
            },
            minWidth: '100'
          },
          {
            prop: 'amount',
            label: '变更金额',
            minWidth: '100'
          },
          {
            prop: 'lastUpdateTime',
            label: '变更日期',
            minWidth: '100'
          },
          {
            prop: 'fileCode',
            label: '文件编号',
            minWidth: '100'
          },
          {
            prop: 'summary',
            label: '摘要',
            minWidth: '100'
          },
          {
            prop: 'sendLetterDeptName',
            label: '发函部门',
            minWidth: '100'
          },
          {
            prop: 'shopName',
            label: '门店',
            minWidth: '100'
          },
          {
            prop: 'constCode',
            label: '门店建设项目号',
            minWidth: '140'
          },
          {
            prop: 'haveReceipt',
            label: '有无小票',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            },
            minWidth: '100'
          },
          {
            prop: 'sendLetterTime',
            label: '发函日期',
            minWidth: '100'
          },
          {
            prop: 'stopOrderStartDate',
            label: '暂停派单开始时间',
            minWidth: '100'
          },
          {
            prop: 'stopOrderEndDate',
            label: '暂停派单结束时间',
            minWidth: '100'
          },
          {
            prop: 'remark',
            label: '说明',
            minWidth: '100'
          },
          {
            prop: 'attachmentName',
            label: '附件名称',
            minWidth: '100'
          }
          // {
          //   prop: 'remark',
          //   label: '附件'
          // }
          // {
          //   label: '操作',
          //   type: 'hidden',
          //   minWidth: '200',
          //   button: [
          //     {
          //       name: '查看预览',
          //       clickFun: this.handlePreview,
          //       className: 'btn-green',
          //       type: 'text'
          //     },
          //     {
          //       name: '附件下载',
          //       clickFun: this.downLoadFile,
          //       className: 'btn-green',
          //       type: 'text'
          //     }
          //   ]
          // }
        ]
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    exportConfig() {
      return [{
        code: 'export',
        name: '施工单位保证金',
        dataMethod: 'post',
        dataApi: '/slm-admin/api/v1/constUnitMargin/export?type=0',
        selectedRows: this.tableSelected,
        paramsRaw: {},
        filtersRaw: this.otherFilters,
        queryField: 'id'
      },
      {
        code: 'exportTemplate',
        name: '施工单位保证金模板',
        async: false,
        templateMethod: 'post',
        templateApi: '/slm-admin/api/v1/constUnitMargin/export?type=1'
      }]
    },
    fileImportConfig() {
      return [{
        code: 'importNew',
        name: '新增施工单位保证金',
        async: false,
        apiUrl: '/slm-admin/api/v1/constUnitMargin/importExcel?type=1'
      },
      {
        code: 'importUpdate',
        name: '修改施工单位保证金',
        async: false,
        apiUrl: '/slm-admin/api/v1/constUnitMargin/importExcel?type=0'
      }]
    }
  },
  created() {
    const obj = this.detailData
    this.formData = obj.data
    this.flag = obj.flag
    this.filterArr = [{ 'id': 'unitCode', 'property': 'unitCode', 'operator': '=', 'value': this.formData.unitCode }]
    this.otherFilters = [...this.filterArr]
    // this.queryData = new FormData()
    this.queryData.append('filtersRaw', JSON.stringify(this.otherFilters))
    this.getTableData(this.queryData)
  },
  activated() {},
  methods: {
    /**
     * 表格合并
     * @param {*} param0
     * row 表格每一行的数据
     * column 表格每一列的数据
     * rowIndex 表格的行索引,不包括表头,从0开始
     * columnIndex 表格的列索引,从0开始
     */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex < 12) {
        // 过滤需要合并的行数
        if (row.spanIndex) {
          // 若rowIndex存在，则合并
          return {
            rowspan: row.spanIndex,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.tableSelected = rows
    },
    getTableData(data) {
      this.tableLoading = true
      getMarginData(data).then(res => {
        if (res.success && res.data && res.data.records) {
          const arr = []
          const noFile = res.data.records.filter(item => !item.attachments || !item.attachments.length)
          noFile.forEach(item => {
            item.spanIndex = 1
          })
          res.data.records.forEach(row => {
            if (row.attachments && row.attachments.length) {
              row.attachments.forEach((item, index) => {
                item.changeType = row.changeType
                item.id = row.id
                item.changeItem = row.changeItem
                item.amount = row.amount
                item.lastUpdateTime = row.lastUpdateTime
                item.fileCode = row.fileCode
                item.summary = row.summary
                item.sendLetterDeptName = row.sendLetterDeptName
                item.shopName = row.shopName
                item.constCode = row.constCode
                item.haveReceipt = row.haveReceipt
                item.sendLetterTime = row.sendLetterTime
                item.remark = row.remark
                if (index === 0) {
                  item.spanIndex = row.attachments.length
                }
                arr.push(item)
              })
            }
          })
          this.tableData = [...arr, ...noFile]
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    handleSearch(data) {
      this.otherFilters = [...this.filterArr, ...data.filtersRaw]
      const params = new FormData()
      params.append('filtersRaw', JSON.stringify(this.otherFilters))
      this.getTableData(params)
    },
    clearSearch() {
      this.otherFilters = [...this.filterArr]
    },
    // 新增/编辑
    handleEdit(data) {
      this.activatedData.unitCode = this.formData.unitCode
      this.activatedData.flag = this.flag
      this.showAdd = true
    },
    // 导入
    handleImport() {
      this.importVisible = true
    },
    // 导入成功
    handleImportSuccess() {
      this.getTableData(this.queryData)
    },
    // 导出
    handleExport() {
      this.exportVisible = true
    },
    goHome() {
      this.showAdd = false
    },
    refreshTable() {
      this.$refs.MarginManagement.initTableData()
    },
    // 关闭查看器
    closeViewer() {
      this.showViewer = false
      this.urlList = []
    },
    handlePreview(file) {
      this.urlList = []
      // const typeName = file.typeName
      const typeArr = file.attachmentUrl.split('.')
      const typeName = file.typeName || typeArr[typeArr.length - 1]
      if (typeName === 'jpg' || typeName === 'jpeg' || typeName === 'png') {
      // 图片预览
        this.showViewer = true
        let picUrl = process.env.VUE_APP_IMG_PREFIX + '/' + file.attachmentUrl
        if (file.attachmentUrl.indexOf('http') !== -1) {
          const url = file.attachmentUrl.split('cn')
          picUrl = process.env.VUE_APP_BPMPIC_PREFIX + url[url.length - 1]
        }
        this.urlList.push(picUrl)
      } else if (typeName === 'pdf' || typeName === 'doc' || typeName === 'docx' || typeName === 'xlsx' || typeName === 'xls') {
        // word,excel预览
        // const newFileUrl = encodeURIComponent(this.url + file.attachmentUrl)
        // window.open(`https://docs.google.com/viewer?url=` + newFileUrl, '_blank')
        if (file.attachmentUrl.indexOf('http') === -1) {
          window.open(`${process.env.VUE_APP_OFFICE_PREFIX}?src=` + process.env.VUE_APP_IMG_PREFIX + file.attachmentUrl)
        } else {
          window.open(`${process.env.VUE_APP_OFFICE_PREFIX}?src=` + file.attachmentUrl)
        }
      } else {
        this.$message.warning('该文件类型不支持预览')
      }
    },
    getFileData(file) {
      // const d = ((file.response || {}).data || {})
      const t = {
        // file
        ...file,
        attachmentName: file.attachmentName || '',
        attachmentUrl: file.attachmentUrl || '',
        createBy: file.createBy || '',
        createTime: file.createTime || '',
        id: file.id || file.uid,
        typeName: file.typeName || (file.attachmentUrl || '').split('.').pop(),
        belongModel: file.belongModel || '',
        attachmentType: file.attachmentType || '',
        configAttachmentId: file.configAttachmentId || ''
      }
      delete t.raw
      return t
    },
    downLoadFile(row) {
      const v = this.getFileData(row)
      this.$downFile(v)
    }
  }
}
</script>

<style lang="scss" scoped>
.top-btn-group{
  text-align: right;
  margin-bottom: 20px;
}
.btn-group{
  display: flex;
  margin-top: 20px;
}
/deep/.el-icon-circle-close:before{
  color: white
}
</style>
